<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>finally</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background: red;
            color: white;
            display: none;
        }
    </style>
</head>
<body>
    <div>loading...</div>
    <script>
        //finally 无论状态是resolve或者reject的话都会执行此动作，和状态无关
        // const promise = new Promise((resolve,reject) => {
        //     reject("hdcms");
        // })
        // .then(msg => {
        //     console.log('resolve');
        // })
        // .catch(msg => {
        //     console.log("reject");
        // }).finally(() => {
        //     console.log("resolve/reject状态都会执行");
        // })
        // ;
        
        function ajax(url){
            return new Promise((resolve,reject) => {
                document.querySelector("div").style.display = 'block';
                let xhr = new XMLHttpRequest();
                xhr.open("GET",url);
                xhr.send();
                xhr.onload = function(){
                    if(this.status == 200){
                        resolve(JSON.parse(this.response));
                    }else{
                        reject(this);
                    }
                }
            });
        }

        //下面使用finally  处理加载状态，当请求完成的时候移除加载图标，请在后台的php文件中添加sleep(2)
        ajax("http://localhost:8888/promise/php/user.php?name=向军")
        .then(user => {
            console.log(user);
        }).catch(error => {
            console.log(error)
        }).finally(() => {
            document.querySelector("div").style.display = 'none';
        });



    </script>
</body>
</html>